import logging
from pyleo.lib.base import *
from pyleo.model.Resource import *
from pyleo.model.lfs_content import *
from pyleo.model.add_reaction import *
from paste.request import construct_url
from operator import itemgetter
from pyleo.lib.formatTime import formatTime,timeOfDay

log = logging.getLogger(__name__)

class MainController(BaseController):

    def index(self,path=None):
        ''' This is the controller for viewing or editing normal wiki or path pages. 
        It is also the controller for receiving trackback pings and comments''' 
        inboundComment,inboundTrackBack=0,0
        if c.requestMethod=='POST':
            self.params=dict(request.params)
            #it's a comment or trackback ...
            if 'author_name' in self.params: 
                inboundComment=True 
            elif 'blog_url' in self.params: 
                inboundTrackBack=True
            elif 'resource' in self.params:
                pass #after editing ...
            else:
                #oops
                response.status_code=403
                return 'Unknown post request'
        #override the basecontroller
        if path: c.path=path
        
        c.content=None
        c.title=None
        
        #ok, what have we got?
        c.dirs,c.files=lfs_content(g.lfs,c.path)
        
        if (c.dirs,c.files)==([],[]): 
            self.getPage(inboundComment=inboundComment,inboundTrackBack=inboundTrackBack)
        else:
            self.contentType='text/html'
       
        if self.contentType=='text/html':
	   return render('path')
        else:
           return c.content

    def getPage(self,inboundComment=0,inboundTrackBack=0):
        
        r=resource(c.path)
        rr=r.get()
        if not r.exists():
            response.status_code=404
            c.content=None
            self.contentType=None
            return
        
        c.content=rr['content']
        c.title=rr['title']
        self.contentType=rr['content_type']
        response.headers['Content-Type']=self.contentType
        c.categories=rr['categories']
        
        tb,com=[],[]
        c.reactions=[]
        
        if 'allow_trackbacks' in rr:
            if inboundTrackBack:
                self.contentType=None
                if rr['allow_trackbacks']=='YES':
                    return add_trackback(self.params,r)
                else: 
                    response.status_code=400
                    return
            if rr['allow_trackbacks']!= 'NO': 
                tb=r.get_annotations('trackback')
                for t in tb:
                    c.reactions.append({'content':t['content'],
                              'url': t['source_url'],
                              'author': t['blog_name'],
                              'time':t['last_modified']})
            c.askTrackBack=rr['allow_trackbacks']=='YES'                  
        elif inboundTrackBack:
            response.status_code=403
            return
                
                              
        if 'allow_comments' in rr:
            if rr['allow_comments']!='NO':
                if inboundComment:
                    if rr['allow_comments']=='YES':
                         if g.math_prompt:
                            import md5
                            verify=self.params["math_verification"]
                            answer=self.params["math_answer"]
                            o=md5.new()
                            o.update(answer)
                            if o.hexdigest()!=verify:
                                response.status_code=400
                                return
		         c.message=add_comment(self.params,r)
                com=r.get_annotations('comment')
                for t in com:
                    c.reactions.append({'content':t['content'],
                            'url':t['author_link'],
                            'author':t['author_name'],
                            'time':t['last_modified']})
            c.askComments=rr['allow_comments']           
        elif inboundComment:
            response.status_code=403
            return
        #we are interleaving the trackbacks and comments 
        c.reactions.sort(key=itemgetter('time'))
        for r in c.reactions: 
            r['timeOfDay']=timeOfDay(r['time'])
            r['date']=formatTime(r['time'])
            
   
        
    def put(self):
        ''' Receive a form from the edit controller and
        replace (or add) the appropriate resource.'''
        if not c.loginStatus: 
            response.status_code=401
            return render('path')
        formDict=dict(request.params)
        target=formDict['resource']
        content=formDict['page_content']
        contentType=formDict['page_content_type']
        keep_last_modified = (formDict['keep_last_modified']=='YES')
        
        title=formDict['title']
        
        leof=g.lfs.get(target)
        
        leof.set_property("page_title", title)
        
        #leof.set_property("author",session['user'])
        leof.set_content(content, contentType, not keep_last_modified)
        leof.set_property('allow_comments',formDict['allow_comments'])
        leof.set_property('allow_trackbacks',formDict['allow_trackbacks'])
        
        c.path=target
        return self.index()
    
    def confirm(self):
        ''' Put an action confirm message (and form) on the current page, and then 
        post the form back to self, with a result. So, we start with:
            confirm?page=blah&action=thing
        produces a form and shows page blah
            confirm?page=blah&action=thing&doit=True
        will result in the action.
        The only action currently supported is delete 
        '''
        params=dict(request.params)
        
        #Let's start with no error handling :-(
        
        actionTarget=params['page']
        r=resource(actionTarget)
        title=(r.get_metadata('page_title') or actionTarget.strip('/'))
        if 'doit' not in params:
            #show the form, or show an error
            r=resource(actionTarget)
            c.action='%s [%s]?'%(params['action'],title)
            c.actionURL=construct_url(request.environ)
            c.actionURL+='&doit'
            print c.actionURL
        else:
            c.actionURL=None
            if params['action']=='delete':
                if 'redirect' in params:
                    redirect=params['redirect']
                else:
                    redirect=g.home_href
                if r.exists():
                    r.leof.delete()
                    h.redirect_to(redirect)               
            c.action='Cannot %s %s!'%(action,actionTarget)
        
        return self.index(actionTarget)
                
    def receiveComment(self):
        ''' Take and load an inbound comment '''
         
            
        
        